package com.blog.Bard.base.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.blog.Bard.base.service.UserService;
import com.blog.Bard.common.controller.BaseController;

@Controller
@RequestMapping("/base/login")
public class LoginController extends BaseController{

	@Autowired
	private UserService userService;
	
	@RequestMapping("/page")
	public String page(Model model) {
		return "login";
	}
	
	/**
	 * 首页
	 * @param model
	 * @return
	 */
	@RequestMapping("/home")
	public String home(Model model) {
		logger.info("execute the LoginController 's home method...");
		return "home/home";
	}
	
	/**
	 * 登录验证
	 * @param req
	 * @param res
	 * @param username
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/checkLogin")
	public Map<String,Object> checkLogin(HttpServletRequest req, HttpServletResponse res
			,String username, String password) {
		logger.info("execute the LoginController 's checkLogin method...");
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("rtn", "fail");
		try {
			Map<String,Object> map = userService.loginCheck(username, password);
			if(map!=null) {
				result = map;
				//HttpSession session = req.getSession();
				//session.setAttribute("ETtoken", map.get("ETtoken"));
				Cookie cookie = new Cookie("ETtoken", (String)map.get("ETtoken"));
				cookie.setPath("/");
				res.addCookie(cookie);
			}else {
				result.put("rtn", "fail");
				result.put("msg", "用户名称或密码错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 登出
	 * @param req
	 * @param res
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/logOut")
	public Map<String,Object> logOut(HttpServletRequest req, HttpServletResponse res) {
		logger.info("execute the LoginController 's logOut method...");
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("rtn", "fail");
		try {
			Cookie[] cookies = req.getCookies();
			if(cookies!=null) {
				for(Cookie c : cookies) {
					c.setMaxAge(0);//设置过期并返回
					c.setPath("/");
					res.addCookie(c);
				}
			}
			result.put("rtn", "ok");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
}
